﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using IndieStudio.BugsBang.Utility;

///Developed By Indie Studio
///https://assetstore.unity.com/publishers/9268
///www.indiestd.com
///info@indiestd.com
 
namespace IndieStudio.BugsBang.Game
{
	[DisallowMultipleComponent]
	public class TargetHint : MonoBehaviour {

		/// <summary>
		/// Whether the target hint is running or not.
		/// </summary>
		public bool isRunning;

		/// <summary>
		/// The target or path object transform.
		/// </summary>
		public Transform target;

		/// <summary>
		/// The image of the hint.
		/// </summary>
		private Image image;

		/// <summary>
		/// The transform fllow 2d component.
		/// </summary>
		private TransformFollow2D transformFllow2D;

		/// <summary>
		/// The max distance for following the current target , otherwise select another target.
		/// </summary>
		private float followDistance = 6;

		// Use this for initialization
		void Start () {

			//Setting up references

			image = GetComponent<Image> ();
			transformFllow2D = GetComponent<TransformFollow2D> ();
			Hide ();
		}
		
		// Update is called once per frame
		void Update () {

			if (!isRunning) {
				return;
			}

			if (target == null) {
				SelectRandomObject ();
				return;
			}

			if (Vector2.Distance (Vector3.zero, target.position) > followDistance) {
				SelectRandomObject ();
			}
		}

		/// <summary>
		/// Select random path object.
		/// </summary>
		private void SelectRandomObject(){
			
			//Let the target follows random path Object in the Paths pool
			PathObject pathObject = Paths.instance.GetWantedPathObjectNearCenter (followDistance);
			if (pathObject != null)
				target = pathObject.transform;
			else
				target = null;

			if (target == null) {
				Hide ();
				return;
			}

			transform.position = target.position;
			Show ();
		}

		/// <summary>
		/// Hide this instance.
		/// </summary>
		public void Hide(){
			target = null;
			image.enabled = false;
			transformFllow2D.Reset();
		}

		/// <summary>
		/// Show this instance.
		/// </summary>
		public void Show(){
			image.enabled = true;
			transformFllow2D.target = target;
			transformFllow2D.Move ();
		}

		/// <summary>
		/// Enable this instance.
		/// </summary>
		public void Enable(){
			isRunning = true;
		}

		/// <summary>
		/// Disable this instance.
		/// </summary>
		public void Disable(){
			isRunning = false;
			Hide ();
		}
	}
}
